﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Topro.WCS
{
    using NLog;
    using System.Threading;
    using Topro.Application;
    using Topro.Entity.Query;
    using Topro.Entity.Response;
    using Topro.Enum;
    using Topro.Service;

    /// <summary>
    /// 主程序
    /// </summary>
    public partial class MainForm : Form
    {
        /// <summary>
        /// 
        /// </summary>
        private AppService appService;

        /// <summary>
        /// 
        /// </summary>
        private Thread threadOne;

        /// <summary>
        /// 日志
        /// </summary>
        private static readonly Logger logger = LogManager.GetLogger("File");

        public MainForm()
        {
            InitializeComponent();

            #region 出入口样式
            //样式
            //dgOutinStation.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;//列宽不自动调整,手工添加列
            ////dgGateWay.RowHeadersWidth = 12;//行标题宽度固定12
            //dgOutinStation.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;//不能用鼠标调整列标头宽度
            ////dgGateWay.AlternatingRowsDefaultCellStyle.BackColor = Color.LemonChiffon;//奇数行背景色
            //dgOutinStation.BackgroundColor = Color.White;//控件背景色
            //dgOutinStation.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列标题居中显示
            //dgOutinStation.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//单元格内容居中显示
            ////行为
            //dgOutinStation.AutoGenerateColumns = false;//不自动创建列
            //dgOutinStation.AllowUserToAddRows = false;//不启用添加
            //dgOutinStation.ReadOnly = true;//不启用编辑
            //dgOutinStation.AllowUserToDeleteRows = false;//不启用删除
            //dgOutinStation.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//单击单元格选中整行
            //dgOutinStation.MultiSelect = false;//不能多选
            //dgOutinStation.AllowUserToResizeRows = false;//禁止用户改变DataGridView1の所有行的行高
            //dgOutinStation.RowTemplate.Height = 100;//设置行高
            ////dgGateWay.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//自动填充
            //dgOutinStation.RowHeadersVisible = false;

            //BindingSource bs = new BindingSource();
            //bs.DataSource = EnumUtil.ToDictionary(typeof(StockStatus));

            //cbbCommandStatus.DataSource = bs;
            //cbbCommandStatus.ValueMember = "key";
            //cbbCommandStatus.DisplayMember = "value";
            //cbbCommandStatus.SelectedIndex = 1;
            #endregion

            #region 指令样式
            //样式
            dgCommand.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;//列宽不自动调整,手工添加列
            dgCommand.RowHeadersWidth = 12;//行标题宽度固定12
            dgCommand.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;//不能用鼠标调整列标头宽度
            //dgCommand.AlternatingRowsDefaultCellStyle.BackColor = Color.LemonChiffon;//奇数行背景色
            dgCommand.BackgroundColor = Color.White;//控件背景色
            dgCommand.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//列标题居中显示
            dgCommand.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;//单元格内容居中显示
            //行为
            dgCommand.AutoGenerateColumns = false;//不自动创建列
            dgCommand.AllowUserToAddRows = false;//不启用添加
            dgCommand.ReadOnly = true;//不启用编辑
            dgCommand.AllowUserToDeleteRows = false;//不启用删除
            dgCommand.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//单击单元格选中整行
            dgCommand.MultiSelect = false;//不能多选
            dgCommand.AllowUserToResizeRows = false;//禁止用户改变DataGridView1の所有行的行高
                                                    //dgCommand.RowTemplate.Height = 200;//设置行高
            #endregion
        }

        #region 事件消息
        /// <summary>
        /// 事件消息
        /// </summary>
        /// <param name="type"></param>
        /// <param name="workStatus"></param>
        /// <param name="info"></param>
        public void Info(int type, Dictionary<string, string> dc)
        {
            try
            {
                if (type == 0)
                {
                    if (dc != null && dc.Count > 0)
                    {
                        this.BeginInvoke((Action)(() =>
                        {
                            txtLog.AppendText(string.Format("{0}  {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), dc.First().Value));
                            txtLog.AppendText(Environment.NewLine);
                            txtLog.ScrollToCaret();
                        }));

                        logger.Info(dc.First().Value);
                    }

                }
                else if (type == 1)
                {
                    this.lblTaskStatus.BackColor = Color.LightGreen;
                    this.lblTaskStatus.Text = "入库索取";
                    //异常
                    btnOneRestore.Enabled = false;
                }
                else if (type == 2)
                {
                    this.lblTaskStatus.BackColor = Color.Green;
                    this.lblTaskStatus.Text = "出库索取";
                    //异常
                    btnOneRestore.Enabled = false;
                }
                else if (type == 3)
                {
                    this.lblTaskStatus.BackColor = Color.Red;
                    this.lblTaskStatus.Text = "异常";
                    //异常
                    btnOneRestore.Enabled = false;
                }
                else if (type == 4)
                {
                    this.lblTaskStatus.BackColor = Color.Yellow;
                    this.lblTaskStatus.Text = "工作中";
                    //异常
                    btnOneRestore.Enabled = false;
                }
                else if (type == 5)
                {
                    this.lblTaskStatus.BackColor = Color.Red;
                    this.lblTaskStatus.Text = "半自动";
                    //异常
                    btnOneRestore.Enabled = false;
                }
                else if (type == 6)
                {

                }
                else if (type == 7)
                {

                }
                else if (type == 8)
                {

                }
                else if (type == 9)
                {

                }
                else if (type == 10)
                {

                }
                else if (type == 90)
                {
                    var count = lstException.Items.Count;
                    if (count > 5)
                    {
                        lstException.Items.RemoveAt(0);
                    }

                    if (dc != null && dc.Count > 0)
                    {
                        var lvi = new ListViewItem();
                        lvi.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        lvi.SubItems.Add(dc.First().Value);
                        //写入
                        lstException.Items.Add(lvi);
                    }

                }
                else if (type == 100)
                {
                    if (dc != null && dc.Count > 0)
                    {
                        var bs = new BindingSource();
                        bs.DataSource = dc;
                    }
                }
            }
            catch(Exception ex)
            {

            }
        }

        /// <summary>
        /// 站台事件消息
        /// </summary>
        /// <param name="station"></param>
        /// <param name="status"></param>
        public void Station(int station, int status)
        {
            try
            {
                if (station == 1)
                    lblOneStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 2)
                    lblTwoStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 3)
                    lblThreeStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 4)
                    lblFourStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 5)
                    lblFiveStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 6)
                    lblSixStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 7)
                    lblSevenStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 8)
                    lblEightStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 9)
                    lblNineStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 10)
                    lblTenStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 11)
                    lblelEvenStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 12)
                    lblTwelveStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 13)
                    lblThirteenStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
                else if (station == 14)
                    lblFourteenStatus.BackColor = status.Equals(1) ? Color.Red : Color.Green;
            }
            catch (Exception ex)
            {
            }
        }
        #endregion

        #region 开始
        /// <summary>
        /// 一号垛机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOneRun_Click(object sender, EventArgs e)
        {
            appService = new AppService();
            appService.infoEvent += new AppService.InfoDelegate(Info);
            appService.stationEvent += new AppService.StationDelegate(Station);
            threadOne = new Thread(appService.init);
            threadOne.Start();

            btnOneRun.Enabled = false;
            btnOneStop.Enabled = true;
        }
        #endregion

        #region 停止垛机
        /// <summary>
        /// 一号垛机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOneStop_Click(object sender, EventArgs e)
        {
            appService.close();

            if (appService != null)
                appService = null;

            threadOne = null;

            btnOneRun.Enabled = true;
            btnOneStop.Enabled = false;

        }
        #endregion

        #region 出入口单元格样式
        /// <summary>
        /// 设置单元格样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgOutinStation_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            try
            {
                if (e.ColumnIndex == 0 || e.ColumnIndex == 1 || e.ColumnIndex == 2)
                {
                    e.CellStyle.ForeColor = Color.Red;
                    e.CellStyle.Font = new Font("宋体", 30, FontStyle.Bold); ;
                }
            }
            catch (Exception ex)
            {

            }
        }
        #endregion

        #region 指令右健单元格菜单
        /// <summary>
        /// 指令右健单元格菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgCommand_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dgCommand.Rows[e.RowIndex].Selected == false)
                    {
                        dgCommand.ClearSelection();
                        dgCommand.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dgCommand.SelectedRows.Count == 1)
                    {
                        dgCommand.CurrentCell = dgCommand.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    //弹出操作菜单
                    msCommand.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }
        #endregion

        #region 指令菜单
        /// <summary>
        /// 完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiComplete_Click(object sender, EventArgs e)
        {
            int count = dgCommand.SelectedRows.Count;
            if(count<=0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //选中行
            var row = dgCommand.SelectedRows;
            if (row == null)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //当前选中的索引
            var index = dgCommand.CurrentRow.Index;
            //当前选择中的行第一个单元格
            var id = (int)dgCommand.Rows[index].Cells[0].Value;
            if (id <= 0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //确定要完成该订单吗
            var dialogResult = MessageBox.Show("确定要完成该指令吗?", "完成确认", MessageBoxButtons.YesNo);

            if(dialogResult == DialogResult.Yes)
            {
                //更新指令状态
                var updateResult = ASRSJOBApp.Instance.DeliveryCompleted(id, (int)CompleteMode.手动);
                if (updateResult.Success)
                    CommandQuery();
                else
                {
                    Info(0, new Dictionary<string, string> { ["1"] = $"[该订单完成失败,{updateResult.Message}]" }); CommandQuery();
                }
            }
        }

        /// <summary>
        /// 删除指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            int count = dgCommand.SelectedRows.Count;
            if (count <= 0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //选中行
            var row = dgCommand.SelectedRows;
            if (row == null)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //当前选中的索引
            var index = dgCommand.CurrentRow.Index;
            //当前选择中的行第一个单元格
            var id = (int)dgCommand.Rows[index].Cells[0].Value;
            if (id <= 0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //确定要完成该订单吗
            var dialogResult = MessageBox.Show("确定要完成该指令吗?", "完成确认", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                //更新指令状态
                var updateResult = ASRSJOBApp.Instance.Delete(id);
                if (updateResult.Success)
                    CommandQuery();
                else
                {
                    Info(0, new Dictionary<string, string> { ["1"] = $"[该订单删除失败,{updateResult.Message}]" }); CommandQuery();
                }
            }
        }

        /// <summary>
        /// 设置站台
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmistation_Click(object sender, EventArgs e)
        {
            int count = dgCommand.SelectedRows.Count;
            if (count <= 0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //选中行
            var row = dgCommand.SelectedRows;
            if (row == null)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //当前选中的索引
            var index = dgCommand.CurrentRow.Index;
            //当前选择中的行第一个单元格
            var id = (int)dgCommand.Rows[index].Cells[0].Value;
            if (id <= 0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //实例化
            frmStation frm = new frmStation();
            //居中
            frm.StartPosition = FormStartPosition.CenterScreen;
            //位置
            frm.Location = new Point(500, 500);
            //弹出模式对话框（子窗体）
            frm.ShowDialog(this);

            if (frm.DialogResult == DialogResult.OK)
            {

            }
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiReset_Click(object sender, EventArgs e)
        {
            int count = dgCommand.SelectedRows.Count;
            if (count <= 0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //选中行
            var row = dgCommand.SelectedRows;
            if (row == null)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //当前选中的索引
            var index = dgCommand.CurrentRow.Index;
            //当前选择中的行第一个单元格
            var id = (int)dgCommand.Rows[index].Cells[0].Value;
            if (id <= 0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //确定要完成该订单吗
            var dialogResult = MessageBox.Show("确定要重置该指令吗?", "删除确认", MessageBoxButtons.YesNo);

            if (dialogResult == DialogResult.Yes)
            {
                //更新指令状态
                var deleteResult = ASRSJOBApp.Instance.UpdateStatus(id, (int)WorkStatus.Zero);
                if (deleteResult.Success)
                {
                    CommandQuery();
                }
                else
                {
                    Info(0, new Dictionary<string, string> { ["1"] = $"[重置该指令失败,{deleteResult.Message}]" }); CommandQuery();
                }
            }
        }

        /// <summary>
        /// 容器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiContainer_Click(object sender, EventArgs e)
        {
            var frm = new frmContainer();
            //居中
            frm.StartPosition = FormStartPosition.CenterScreen;
            //位置
            frm.Location = new Point(500, 500);
            //弹出模式对话框（子窗体）
            frm.ShowDialog(this);
        }

        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TSMIClear_Click(object sender, EventArgs e)
        {
            //var result = appService.Clear();
            //if(result.Success)
            //{
            //    MessageBox.Show(result.Message, "提示");
            //}
            //else
            //{
            //    MessageBox.Show($"清空地址失败.{result.Message}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //}
        }

        /// <summary>
        /// 台车移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TSMICar_Click(object sender, EventArgs e)
        {
            //实例化
            frmCar frm = new frmCar();
            //居中
            frm.StartPosition = FormStartPosition.CenterScreen;
            //位置
            frm.Location = new Point(500, 500);
            //弹出模式对话框（子窗体）
            frm.ShowDialog(this);

            if (frm.DialogResult == DialogResult.OK)
            {

            }
        }
        #endregion

        #region 指令查询
        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.CommandQuery();
        }

        /// <summary>
        /// 指令查询
        /// </summary>
        public void CommandQuery()
        {
            try
            {
                //参数
                var query = new ASRSJOBQuery();
                //获取选中的值
                query.States = new List<int>()
                {
                    (int)ASRSJOBStatus.待处理,
                    (int)ASRSJOBStatus.操作中
                };

                //查询
                var list = ASRSJOBApp.Instance.ASRSJOBPager(query);
                //绑定数据
                this.dgCommand.DataSource = new BindingList<ASRSJOBQueryResponse>(list);
            }
            catch(Exception ex)
            {

            }

        }
        #endregion

        #region 关闭窗体事件
        /// <summary>
        /// 关闭窗体事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (appService != null)
            {
                appService.close();
                appService = null;
            }
            threadOne = null;
            
            this.Dispose();
            this.Close();
            Process.GetCurrentProcess().Kill();
        }
        #endregion

        #region 指令双击事件
        /// <summary>
        /// 指令双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgCommand_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int count = dgCommand.SelectedRows.Count;
            if (count <= 0)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //选中行
            var row = dgCommand.SelectedRows;
            if (row == null)
                MessageBox.Show("请选择要完成的行.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //当前选中的索引
            var index = dgCommand.CurrentRow.Index;
            //当前选择中的行第一个单元格
            var id = (int)dgCommand.Rows[index].Cells[0].Value;
            if (id <= 0)
            {
                Info(0, new Dictionary<string, string> { ["0"] = $"[设置流水号] [请选择要完成的行.]" }); return;
            }
            //asrsjob
            var asrsjob = ASRSJOBApp.Instance.GetById(id);
            if (asrsjob == null)
            {
                Info(0, new Dictionary<string, string> { ["0"] = $"[设置流水号] [任务查询失败.]" }); return;
            }
            if (asrsjob.TYPE == "Out")
            {
                Info(0, new Dictionary<string, string> { ["0"] = $"[设置流水号] [出库任务不需要设置流水号.]" }); return;
            }
            //确定要完成该订单吗
            var dialogResult = MessageBox.Show("确定要手动设置流水?", "完成确认", MessageBoxButtons.YesNo);
            if (dialogResult == DialogResult.Yes)
            {
                if (string.IsNullOrEmpty(asrsjob.ORIPORT))
                {
                    Info(0, new Dictionary<string, string> { ["0"] = $"[入库] [指令错误(from):{asrsjob.ORIPORT}为空]" }); return;
                }

                var oriport = asrsjob.ORIPORT.Split('-');
                //验证长度
                if (oriport.Length < 4)
                {
                    Info(0, new Dictionary<string, string> { ["0"] = $"[入库] [指令错误(from):{asrsjob.TARPORT}长度验证失败]" }); return;
                }
                //入库站台
                var stationId = int.Parse(oriport[3]);
                if (appService == null)
                    Info(0, new Dictionary<string, string> { ["0"] = $"堆垛机还未启用" });
                else
                    appService.SetStation(stationId, int.Parse(asrsjob.CTNCODE));
            }
        }
        #endregion

        #region 异常复位
        /// <summary>
        /// 异常复位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOneRestore_Click(object sender, EventArgs e)
        {
            appService.Restore();
        }
        #endregion
    }
}
